<template>
  <e-panel v-bind="opts">
    <template #bottom>
      <e-form ref="formRef" v-bind="formProps">
        <n-space align="end" style="width: 100%">
          <n-button @click="() => previewHandle()">预览</n-button>
          <e-dict-input v-model:value="codeModel" code="#gen_module" style="width: 200px" />
        </n-space>
      </e-form>
      <gen-preview ref="genPreviewRef" />
    </template>
  </e-panel>
</template>

<script lang="ts" setup>
  import Model from './model'
  import { usePanel } from '@/components/ext'
  import { GeneratorApi, GenPreviewFile, GenPreviewProps } from '@/views/gen/table/model'
  import GenPreview from '@/views/gen/table/comp/GenPreview.vue'
  import { GeneratorData, GenModuleApi } from '@/views/gen/module/model'
  import type { ButtonActions } from '@/components/ActionButton/commonActions'

  defineOptions({
    name: 'GenTemplateList'
  })
  const rowActions: ButtonActions = [
    {
      action: 'addChild',
      html: '预览',
      text: true,
      type: 'primary',
      perms: 'insert',
      handle: ({ row }) => {
        previewHandle(row)
      }
    },
    'edit',
    'delete'
  ]
  const opts = usePanel(Model, { formProps: { cols: 4 }, tableProps: { actions: rowActions } })
  const formRef = opts.refs.formRef
  const formProps = opts.commProps.formProps

  const genPreviewRef = useCompRef(GenPreview)

  const previewTable = {
    id: '1',
    name: 'sys_test',
    moduleCode: 'sys'
  }

  const codeModel = ref<string>('sys')

  const previewHandle = async (fd?: Model) => {
    const formData = fd ?? formRef.value!.getFormData()
    if (!codeModel.value || !formData.fileName || !formData.name) {
      window.$message.warning('信息不全')
      return
    }
    const resp = await GenModuleApi.getModule({ code: codeModel.value })
    if (!resp.success) {
      return
    }
    const data: GeneratorData = {
      tableId: previewTable.id,
      moduleCode: codeModel.value ?? previewTable.moduleCode,
      templateType: formData.type!,
      templateContents: [formData.content ?? ''],
      files: [formData.name]
    }

    const { data: files } = await GeneratorApi.generator(data)

    const file: GenPreviewFile = files[0]

    const genPreviewProps: GenPreviewProps = {
      files: [
        {
          name: file.name ?? '',
          content: file.content ?? '',
          outputName: file.outputName ?? ''
        }
      ],
      name: formData.name ?? ''
    }
    genPreviewRef.value?.open(genPreviewProps)
  }
</script>

<style scoped>
  .code-preview {
    padding: 0 20px;
  }
</style>
